class River:
    
    """
    Definition of the River class.
    
    The minimum requirement is 'id,' a USGS station number.
    
    3/14/2014  Parker MacCready
    """
    
    def __init__(self, id = 0, name = ''):
        try:
            self.id = int(id)
            self.name = str(name)
            self.Q = []
            self.T = []             
        except:
            print('Error: id needs to be an integer')
                           
    def __repr__(self):
        """This displays when you type str(instance).
        """
        return "River(%d)" % (self.id)
        
    def get_data(self):
        """This tries to get the data from the web.
        """
        # library to do http requests:
        import urllib2
        
        # XML parsing code
        import xml.etree.ElementTree as ET
        
        # define the url string
        site_str = 'http://waterservices.usgs.gov/nwis/iv/'
        format_str = '?format=waterml,1.1'
        sites_str = '&sites='
        site = str(self.id)
        period_str = '&period='
        period = 'P6D' # 'P6D' would be 6 days ago to the present
        params_str = '&parameterCd='
        params = '00060' # '00060' is discharge in cubic ft per second
        # 00010 is temperature degC, but it only exists for the Cedar River!
        
        # create the url string
        # NOTE: you use parenthesis to make a long string
        url_str = (site_str + format_str + sites_str + site 
        + period_str + period + params_str + params)
        
        # print(url_str) # for debugging
        
        # get the XML file and parse it
        try:
            file = urllib2.urlopen(url_str, timeout = 5)
            tree = ET.parse(file)
            root = tree.getroot()                          
            import pandas as pd
            for elem in root.findall('.//{http://www.cuahsi.org/waterML/1.1/}value'):
               #t.extend([parse(elem.get('dateTime'))])
               self.T.extend([pd.to_datetime(elem.get('dateTime'))])
               self.Q.extend([0.0283168466 * float(elem.text)]) # convert ft3 s-1 to m3 s-1      
        except:
            print('Could not get or parse XML for ' + self.name) 
        
        # turn this on to see the XML file contents
        if False:  
           for e0 in root:
               print 'ROOT*' + str(e0.attrib) + ' ' + str(e0.text)
               for e1 in e0:
                   print 'Child>> ' + str(e1.attrib) + ' ' + str(e1.text)
                   for e2 in e1:
                       print 'grandchild---> ' + str(e2.attrib) + ' ' + str(e2.text)
                
    
           
           
        
        
        
